package com.soup.common.support.spring.advice;

import com.soup.common.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回格式
 *
 * @author zhaoyi
 */
@Slf4j
@RestControllerAdvice
public class ResultResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object returnObj, MethodParameter methodParameter,
                                  MediaType mediaType, Class<? extends HttpMessageConverter<?>> converterType,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        log.info("returnObj class: {}", returnObj.getClass());

        // 不需要包装的返回对象的情况：本身就是 Result；ResponseEntity对象；MediaType是TEXT_HTML
        boolean unWrappered = (returnObj instanceof Result) || (returnObj instanceof ResponseEntity)
                || mediaType.includes(MediaType.TEXT_HTML);

        Object trueReturnObj = returnObj;
        if (!unWrappered) {
            trueReturnObj = new Result().success(returnObj);
        }

        return trueReturnObj;
    }
}